/*
 * mainwindow.cpp - Main window GUI
 *
 * Copyright (C) 2010-2011 Serge Begger
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    setWindowFlags(Qt::FramelessWindowHint);
    ui->setupUi(this);

    settings = new QSettings("carpc", "general", this);
    settings->setPath(QSettings::IniFormat,QSettings::UserScope,"carpc");

    currVolume = settings->value("Volume").toInt();

    QString style = settings->value("style").toString();
    QStyle *qstyle = NULL;
    if (style.size())
    {
            qstyle = QStyleFactory::create( style );
            if (qstyle)
                    QApplication::setStyle( qstyle );
    }

    prewWidgetIndex = 0;
    prewMMWidgetIndex = 0;
    prewEQWidgetIndex = 0;
    mmplayer = 0;
    radiofm = 0;
    analogTV = 0;
    naviWidget = 0;
    configWidget = 0;
    freessmWidget = 0;
    dvbtWidget = 0;

    fserver = new festivalStarter(this);

    spengine = new speechengine(this);
    spengine->start();

    phoneWidget = new handsfree(this);
    phoneWidget->startHFS();
    connect(phoneWidget, SIGNAL(hideWidget()),this,SLOT(hideMmWidget()));
    connect(phoneWidget, SIGNAL(muteSound(bool)),this,SLOT(phoneCall(bool)));
    ui->stackedWidget->addWidget(phoneWidget);

    Mixer = new mixer(this);
    connect(Mixer,SIGNAL(EQSliderValue(double*)),this,SLOT(changeEQ(double*)));
    connect(Mixer, SIGNAL(hideWidget()),this,SLOT(hideEqWidget()));
    ui->stackedWidget->addWidget(Mixer);

    if (currVolume == 0) {
        currVolume = 20;
    }
    volSlider = new gslider(ui->frameVolSlider,true);
    volSlider->setGeometry(ui->frameVolSlider->geometry());
    updateVolSlider();

    ssdeact = new ScreenSaverDeactivator(this);
    ssavers = ssdeact->screenSaverCheck();
    if (ssavers["xscreensaver"])
        ssdeact->xDeactivate();
    if (ssavers["gnome-screensaver"])
        ssdeact->gDeactivate();

    powerDlg = new poweroff(this);
    connect(powerDlg, SIGNAL(disableMedia()), this, SLOT(destroyAllWidget()));
    connect(powerDlg, SIGNAL(hideWidget()),this,SLOT(hideMmWidget()));
    ui->stackedWidget->addWidget(powerDlg);

    pw_off_notif = new poweroffnotifer(this);
    connect(pw_off_notif,SIGNAL(pwrOff()),this,SLOT(powerOff()));

    typeStyleShhet = "day";
    QFile guiFile(QDir::homePath() + "/.config/carpc/style_day.qss");
    if (guiFile.open(QIODevice::ReadOnly))
    {
        QString css(guiFile.readAll());
        qApp->setStyleSheet(css);
    }
    gps = new gpsinterface(this);
    connect(gps, SIGNAL(riseset()), this ,SLOT(changeStyleSheet()));

    uDiface = new udiskInterface(this);
    connect(uDiface, SIGNAL(volumeAdded(QString)), this ,SLOT(volumeAdded(QString)));
}

MainWindow::~MainWindow()
{
    settings->setValue("Volume",currVolume);
    if (ssavers["xscreensaver"])
        ssdeact->xActivate();
    if (ssavers["gnome-screensaver"])
        ssdeact->gActivate();
    delete ui;
}

void MainWindow::powerOff() {
    destroyMmWidget();
    QApplication::quit();
}

void MainWindow::changeStyleSheet()
{
    bool change = false;
    if (gps->nowNight() && typeStyleShhet == "day") {
        typeStyleShhet = "night";
        change = true;
    }
    else if (gps->nowDay() && typeStyleShhet == "night") {
        typeStyleShhet = "day";
        change = true;
    }

    if (!change)
        return;

    QFile guiFile(QDir::homePath() + "/.config/carpc/style_" + typeStyleShhet + ".qss");
    if (guiFile.open(QIODevice::ReadOnly))
    {
        QString css(guiFile.readAll());
        qApp->setStyleSheet(css);
    }
}

void MainWindow::changeEQ(double *band)
{
    if(mmplayer)
        mmplayer->gstEngine->setFreq(band);
    else if (radiofm)
        radiofm->gstEngine->setFreq(band);
    else if (analogTV)
        analogTV->gstEngine->setFreq(band);
    else if (dvbtWidget)
        dvbtWidget->gstEngine->setFreq(band);
}

void MainWindow::setEQValue()
{
    double band[10];
    Mixer->EQcurValue(band);
    changeEQ(band);
}

void MainWindow::on_volUpButton_pressed()
{
    currVolume = currVolume + 5;
    if (currVolume > volSlider->maximum())
        currVolume = volSlider->maximum();
    setMmVolume();
}

void MainWindow::on_volDwButton_pressed()
{
    currVolume = currVolume - 5;
    if (currVolume < volSlider->minimum())
        currVolume = volSlider->minimum();
    setMmVolume();
}

void MainWindow::updateVolSlider() {
    volSlider->setValue(currVolume);
}

void MainWindow::setMmVolume() {    
    updateVolSlider();
    if(mmplayer){
        mmplayer->setVolume(currVolume);
    } else if (radiofm) {
        radiofm->setVolume(currVolume);
    } else if (analogTV) {
        analogTV->setVolume(currVolume);
    } else if (dvbtWidget) {
        dvbtWidget->setVolume(currVolume);
    }
}

void MainWindow::phoneCall(bool mute)
{
    ui->muteButton->setChecked(mute);
    muteSound(mute);
}

void MainWindow::muteSound(bool muted)
{
    if(mmplayer)
        mmplayer->gstEngine->mute(muted);
    else if (radiofm)
        radiofm->gstEngine->mute(muted);
    else if (analogTV)
        analogTV->gstEngine->mute(muted);
    else if (dvbtWidget)
        dvbtWidget->gstEngine->mute(muted);
}

void MainWindow::on_actWidgButton_pressed()
{
    if (ui->stackedWidget->currentWidget() == naviWidget ||
        ui->stackedWidget->currentWidget() == phoneWidget ||
        ui->stackedWidget->currentWidget() == Mixer ||
            ui->stackedWidget->currentIndex() == 0 )
            prewMMWidgetIndex = ui->stackedWidget->currentIndex();

    if(mmplayer)
        ui->stackedWidget->setCurrentWidget(mmplayer);
    else if (radiofm)
        ui->stackedWidget->setCurrentWidget(radiofm);
    else if (analogTV)
        ui->stackedWidget->setCurrentWidget(analogTV);
    else if (dvbtWidget)
        ui->stackedWidget->setCurrentWidget(dvbtWidget);
}

void MainWindow::on_soundSetButton_pressed()
{
    prewEQWidgetIndex = ui->stackedWidget->currentIndex();
    ui->stackedWidget->setCurrentWidget(Mixer);
    ui->soundSetButton->setDisabled(true);
}

void MainWindow::hideEqWidget()
{
    ui->soundSetButton->setDisabled(false);
    ui->stackedWidget->setCurrentIndex(prewEQWidgetIndex);
}

void MainWindow::on_muteButton_toggled(bool checked)
{
    if (checked)
        ui->muteButton->setIcon(QIcon(QString::fromUtf8(":/buttons/res/kmixdocked_mute.png")));
    else
        ui->muteButton->setIcon(QIcon(QString::fromUtf8(":/buttons/res/kmixdocked.png")));
    muteSound(checked);
}

void MainWindow::on_playerButton_pressed()
{
    if (!mmplayer) {
        destroyMmWidget();
        mmplayer = new player(this);
        ui->stackedWidget->addWidget(mmplayer);
        currVolume = mmplayer->currVolume;
        updateVolSlider();
        Mixer->EQcurValue(mmplayer->currEQBand);
        mmplayer->init();
        connect(mmplayer, SIGNAL(destroyed()),this,SLOT(closeMmWidget()));
        connect(mmplayer, SIGNAL(hideWidget()),this,SLOT(hideMmWidget()));
    }
    prewWidgetIndex = ui->stackedWidget->currentIndex();
    ui->stackedWidget->setCurrentWidget(mmplayer);
}

void MainWindow::volumeAdded(QString path) {
    if (!mmplayer)
        on_playerButton_pressed();
    mmplayer->playPath(path);
}

void MainWindow::on_radioButton_pressed()
{
    if (!radiofm) {
        destroyMmWidget();
        radiofm = new Radio(this);
        if (!radiofm->initRadio()) {
            radiofm = 0;
            ui->stackedWidget->setCurrentIndex(0);
            return;
        }
        currVolume = radiofm->currVolume;
        updateVolSlider();
        ui->stackedWidget->addWidget(radiofm);
        connect(radiofm, SIGNAL(destroyed()),this,SLOT(closeMmWidget()));
        connect(radiofm, SIGNAL(hideWidget()),this,SLOT(hideMmWidget()));
        setEQValue();
    }
    prewWidgetIndex = ui->stackedWidget->currentIndex();
    ui->stackedWidget->setCurrentWidget(radiofm);
}

void MainWindow::on_tvButton_pressed()
{    
    if (!analogTV) {
        destroyMmWidget();
        analogTV = new analogtv(this);
        if (!analogTV->init()) {
            analogTV = 0;
            ui->stackedWidget->setCurrentIndex(0);
            return;
        }
        currVolume = analogTV->currVolume;
        setMmVolume();
        ui->stackedWidget->addWidget(analogTV);
        connect(analogTV, SIGNAL(destroyed()),this,SLOT(closeMmWidget()));
        connect(analogTV, SIGNAL(hideWidget()),this,SLOT(hideMmWidget()));
        setEQValue();
    }
    prewWidgetIndex = ui->stackedWidget->currentIndex();
    ui->stackedWidget->setCurrentWidget(analogTV);
}

void MainWindow::on_dvbtButton_pressed()
{
    if (!dvbtWidget) {
        destroyMmWidget();
        dvbtWidget = new dvbt(this);
        if (!dvbtWidget->init()) {
            dvbtWidget = 0;
            ui->stackedWidget->setCurrentIndex(0);
            return;
        }
        currVolume = dvbtWidget->currVolume;
        updateVolSlider();
        ui->stackedWidget->addWidget(dvbtWidget);
        connect(dvbtWidget, SIGNAL(destroyed()),this,SLOT(closeMmWidget()));
        connect(dvbtWidget, SIGNAL(hideWidget()),this,SLOT(hideMmWidget()));
        setEQValue();
    }
    prewWidgetIndex = ui->stackedWidget->currentIndex();
    ui->stackedWidget->setCurrentWidget(dvbtWidget);
}

void MainWindow::on_naviButton_pressed()
{
    if (!naviWidget) {
        naviWidget = new navi(this);
        if (!naviWidget->init()) {
            naviWidget = 0;
            ui->stackedWidget->setCurrentIndex(0);
            return;
        }
        ui->stackedWidget->addWidget(naviWidget);
        connect(naviWidget,SIGNAL(speechText(QByteArray)),this,SLOT(speechText(QByteArray)));
        connect(naviWidget, SIGNAL(clientClosed()),this,SLOT(destroyNaviWidget()));
    }
    prewWidgetIndex = ui->stackedWidget->currentIndex();
    ui->stackedWidget->setCurrentWidget(naviWidget);
}

void MainWindow::on_handsFreeButton_pressed()
{
    if (phoneWidget->error)
        return;
    if (!phoneWidget->currState)
        return;
    prewWidgetIndex = ui->stackedWidget->currentIndex();
    ui->stackedWidget->setCurrentWidget(phoneWidget);
}

void MainWindow::on_diagButton_pressed()
{
    if (!freessmWidget) {
        freessmWidget = new FreeSSM(this);
        ui->stackedWidget->addWidget(freessmWidget);
        connect(freessmWidget, SIGNAL(destroyed()),this,SLOT(destroyFreeSSMWidget()));
    }
    prewWidgetIndex = ui->stackedWidget->currentIndex();
    ui->stackedWidget->setCurrentWidget(freessmWidget);
}

void MainWindow::connectHFSDevice()
{
   phoneWidget->startHFS();
}

void MainWindow::disconnectHFSDevice()
{
   phoneWidget->stopHFS();
}

void MainWindow::on_configButton_pressed()
{    
    ui->downFrame->setDisabled(true);
    if (!configWidget) {
        destroyAllWidget();
        configWidget = new configure(this);
        ui->stackedWidget->addWidget(configWidget);
        connect(configWidget, SIGNAL(destroyed()),this,SLOT(destroyCfgWidget()));
        connect(configWidget, SIGNAL(connHFSDev()),this,SLOT(connectHFSDevice()));        
        connect(configWidget, SIGNAL(disconnHFSDev()),this,SLOT(disconnectHFSDevice()));
    }
    ui->stackedWidget->setCurrentWidget(configWidget);
}

void MainWindow::on_powerButton_pressed()
{
    ui->downFrame->setDisabled(true);
    prewWidgetIndex = ui->stackedWidget->currentIndex();
    ui->stackedWidget->setCurrentWidget(powerDlg);
}

void MainWindow::hideMmWidget()
{    
    if(mmplayer)
        ui->actWidgButton->setIcon(QIcon(QString::fromUtf8(":/buttons/res/multimedia.png")));
    else if (radiofm)
        ui->actWidgButton->setIcon(QIcon(QString::fromUtf8(":/buttons/res/radio.png")));
    else if (analogTV)
        ui->actWidgButton->setIcon(QIcon(QString::fromUtf8(":/buttons/res/tv.png")));
    else if (dvbtWidget)
        ui->actWidgButton->setIcon(QIcon(QString::fromUtf8(":/buttons/res/dvbt_logo.png")));


    if (naviWidget) {
        QEventLoop loop; QTimer::singleShot(200, &loop, SLOT(quit())); loop.exec();
        ui->stackedWidget->setCurrentWidget(naviWidget);
    } else
        ui->stackedWidget->setCurrentIndex(prewMMWidgetIndex);

    ui->downFrame->setDisabled(false);
}

void MainWindow::destroyCfgWidget()
{
    ui->stackedWidget->removeWidget(configWidget);
    configWidget = 0;
    ui->stackedWidget->setCurrentIndex(0);
    ui->downFrame->setDisabled(false);
}

void MainWindow::destroyNaviWidget()
{
    ui->stackedWidget->removeWidget(naviWidget);
    naviWidget = 0;
    ui->stackedWidget->setCurrentIndex(prewWidgetIndex);
}

void MainWindow::destroyFreeSSMWidget()
{
    ui->stackedWidget->removeWidget(freessmWidget);
    freessmWidget = 0;
    ui->stackedWidget->setCurrentIndex(0);
}

void MainWindow::destroyAllWidget()
{
    destroyMmWidget();
    if (naviWidget != 0)
        destroyNaviWidget();
    if (freessmWidget != 0)
        destroyFreeSSMWidget();
}

void MainWindow::destroyMmWidget()
{
    if(mmplayer)
        mmplayer->~player();
     else if (radiofm)
        radiofm->~Radio();
     else if (analogTV)
        analogTV->~analogtv();
     else if (dvbtWidget)
        dvbtWidget->~dvbt();
    ui->actWidgButton->setIcon(QIcon(QString::fromUtf8(":/buttons/res/help-browser.png")));
    ui->stackedWidget->setCurrentIndex(prewWidgetIndex);
}

void MainWindow::closeMmWidget()
{
    if(mmplayer) {
        ui->stackedWidget->removeWidget(mmplayer);
        mmplayer = 0;
    } else if (radiofm) {
        ui->stackedWidget->removeWidget(radiofm);
        radiofm = 0;
    } else if (analogTV) {
        ui->stackedWidget->removeWidget(analogTV);
        analogTV = 0;
    } else if (dvbtWidget) {
        ui->stackedWidget->removeWidget(dvbtWidget);
        dvbtWidget = 0;
    }
    ui->actWidgButton->setIcon(QIcon(QString::fromUtf8(":/buttons/res/help-browser.png")));
    ui->stackedWidget->setCurrentIndex(prewWidgetIndex);
}

void MainWindow::speechText(QByteArray text) {
        spengine->speechText(text, Mixer->speechVolume());
}
